package cm.just;

import java.sql.*;

public class JDBC01 {

    //1.注册驱动
    public static void regist() {
        try{
            //加载class文件到jvm内存中（类加载）
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("注册成功");
        }catch(ClassNotFoundException exception){
            System.out.println("类名不正确");
            exception.printStackTrace();
        }
    }

    //2.连接数据库
    public static Connection getConnection(){
         String url = "jdbc:mysql://localhost:3306/javaweb?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";
         String user = "root";
         String password = "root";
         Connection conn = null;

        try {
            conn = DriverManager.getConnection(url,user,password);
            System.out.println("连接成功" + conn);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    //3.新增数据
    public static void insert(Connection conn){

        Statement statement = null;
        try {
            //创建状态集对象
            statement = conn.createStatement();
            //执行sql
            String sql = "insert into t_user(username,password) values ('小明','123456')";
            //执行增删改操作 使用
            int count = statement.executeUpdate(sql);
            System.out.println("Query OK,"+ count+ "rows affected");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    //4.查询数据
    public static void selectALl(Connection conn) throws SQLException {
        Statement st = null;
        ResultSet rs = null;
        String sql = "select id,username,password from t_user";
        st = conn.createStatement();
        rs = st.executeQuery(sql);
        while(rs.next()){
            int id = rs.getInt("id");
            String username = rs.getString("username");
            String password = rs.getString("password");
            System.out.println("用户编号:" + id + " 用户名: "+username + " 密码 " +password);
        }
    }

    public static void main(String[] args) throws SQLException {
        regist();
        Connection connection = getConnection();
//        insert(connection);
        selectALl(connection);
    }
}
